<template>
    <div class="chat-container">
        <!-- 聊天记录区域 -->
        <div class="chat-messages" ref="messageContainer">
            <div v-for="(message, index) in messages" :key="index"
                :class="['message-item', message.type === 'response' ? 'response' : 'question']">
                <div class="message-content" :class="message.type">
                    <div class="message-header">
                      <div class="avatar">
                        <img v-if="message.type === 'response'" src="@/assets/logo.png" alt="Bot">
                        <el-avatar
                            v-else
                            :src="userStore.avatar"
                            icon="el-icon-user"
                            :size="36"
                        ></el-avatar>
                      </div>
                      <div class="message-info">
                            <span class="sender">{{ message.type === 'response' ? 'Response' : 'You' }}</span>
                            <span class="time">{{ message.time }}</span>
                        </div>
                    </div>
                    <div class="text-content">{{ message.content }}</div>
                    <div v-if="message.type === 'response'" class="message-actions">
                        <div class="action-buttons">
                            <el-tooltip content="重新生成" placement="top">
                                <i class="el-icon-refresh-right action-icon" @click="regenerateResponse(index)"></i>
                            </el-tooltip>
                            <el-tooltip content="复制" placement="top">
                                <i class="el-icon-document-copy action-icon" @click="copyToClipboard(message.content)"></i>
                            </el-tooltip>
                            <el-tooltip content="收藏" placement="top">
                                <i class="el-icon-star-off action-icon"></i>
                            </el-tooltip>
                        </div>
                    </div>
                    <div v-if="message.type === 'response' && message.relatedQuestions && message.relatedQuestions.length > 0" class="related-questions">
                        <div v-for="(question, qIndex) in message.relatedQuestions" :key="qIndex"
                            class="related-question" @click="askQuestion(question)">
                            {{ question }}
                        </div>
                    </div>
                </div>
            </div>
            <!-- Loading indicator -->
            <div v-if="isLoading" class="message-item response">
                <div class="message-content response">
                    <div class="message-header">
                        <div class="avatar">
                            <img src="@/assets/logo.png" alt="Bot">
                        </div>
                        <div class="message-info">
                            <span class="sender">Response</span>
                        </div>
                    </div>
                    <div class="text-content loading">
                        <span class="dot"></span>
                        <span class="dot"></span>
                        <span class="dot"></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- 输入区域 -->
        <div class="chat-input-section">
            <div class="input-wrapper">
                <div class="input-container">
                    <div class="input-field">
                        <el-input type="text" v-model="currentInput" placeholder="Ask questions, or type ? for commands"
                            @keyup.enter="sendMessage" class="main-input" :disabled="isLoading">
                            <template #prefix>
                                <i class="el-icon-search"></i>
                            </template>
                            <template #suffix>
                                <i class="el-icon-microphone"></i>
                            </template>
                        </el-input>
                    </div>
                    <div class="send-button" @click="sendMessage" :class="{ disabled: isLoading }">
                        <i class="el-icon-position"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { chatService } from '@/utils/request'
import { ElMessage } from 'element-plus'
import profileImg from '@/assets/images/profile.jpg'

export default {
  name: 'Chat',
  data() {
    return {
      currentInput: '',
      messages: [],
      conversation_id: null,
      isLoading: false,
      userStore: {
        avatar: profileImg
      }
    }
  },
    methods: {
        formatTime() {
            const now = new Date();
            return `${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日 ${now.getHours()}:${String(now.getMinutes()).padStart(2, '0')}`;
        },
        async sendMessage() {
            if (!this.currentInput.trim()) return;

            // Add user question to messages
            this.messages.push({
                type: 'question',
                content: this.currentInput,
                time: this.formatTime()
            });

            const question = this.currentInput;
            this.currentInput = '';
            this.isLoading = true;

            try {
                const response = await chatService({
                    url: '/api/chat',
                    method: 'post',
                    data: {
                        question,
                        conversation_id: this.conversation_id,
                        user_id: 'test-user-001'
                    }
                });

                // Update conversation ID for context maintenance
                if (response.conversation_id) {
                    this.conversation_id = response.conversation_id;
                }

                // Add response to messages
                this.messages.push({
                    type: 'response',
                    content: response.content,
                    time: this.formatTime(),
                    relatedQuestions: response.relatedQuestions || []
                });
            } catch (error) {
                // Add error message to chat
                this.messages.push({
                    type: 'response',
                    content: error.message || '抱歉，发生了一些错误。请稍后重试。',
                    time: this.formatTime(),
                    relatedQuestions: []
                });
                console.error('Chat error:', error);
            } finally {
                this.isLoading = false;
                this.scrollToBottom();
            }
        },
        async regenerateResponse(index) {
            if (this.isLoading) return;

            // Find the corresponding question message
            let questionIndex = index;
            while (questionIndex >= 0 && this.messages[questionIndex].type !== 'question') {
                questionIndex--;
            }

            if (questionIndex < 0) {
                ElMessage.warning('无法找到对应的问题');
                return;
            }

            const question = this.messages[questionIndex].content;
            this.isLoading = true;

            try {
                const response = await chatService({
                    url: '/api/chat',
                    method: 'post',
                    data: {
                        question,
                        conversation_id: this.conversation_id,
                        user_id: 'test-user-001'
                    }
                });

                // Update the existing response
                this.messages[index] = {
                    type: 'response',
                    content: response.content,
                    time: this.formatTime(),
                    relatedQuestions: response.relatedQuestions || []
                };
            } catch (error) {
                ElMessage.error(error.message || '重新生成失败，请稍后重试');
                console.error('Regenerate error:', error);
            } finally {
                this.isLoading = false;
            }
        },
        async copyToClipboard(text) {
            try {
                await navigator.clipboard.writeText(text);
                ElMessage.success('已复制到剪贴板');
            } catch (err) {
                ElMessage.error('复制失败，请手动复制');
                console.error('Copy error:', err);
            }
        },
        askQuestion(question) {
            this.currentInput = question;
            this.sendMessage();
        },
        scrollToBottom() {
            this.$nextTick(() => {
                const container = this.$refs.messageContainer;
                if (container) {
                    container.scrollTop = container.scrollHeight;
                }
            });
        }
    },
    mounted() {
        // If there's an initial question (from homepage), send it
        const initialQuestion = this.$route.query.question;
        if (initialQuestion) {
            this.currentInput = initialQuestion;
            this.sendMessage();
        }
    }
}
</script>

<style lang="scss" scoped>
.chat-container {
    height: calc(100vh - 50px);
    display: flex;
    flex-direction: column;
    background-color: #f5f7fa;
    padding: 20px;
}

.chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    margin-bottom: 20px;

    .message-item {
        margin-bottom: 30px;

        .message-content {
            max-width: 800px;
            margin: 0 auto;

            &.response {
                background-color: #e8f6f0;
                border-radius: 12px;
                padding: 20px;
            }

            .message-header {
                display: flex;
                align-items: center;
                margin-bottom: 12px;

                .avatar {
                    width: 36px;
                    height: 36px;
                    margin-right: 12px;

                    img {
                        width: 100%;
                        height: 100%;
                        border-radius: 50%;
                    }
                }

                .message-info {
                    .sender {
                        font-weight: 500;
                        margin-right: 8px;
                    }

                    .time {
                        color: #999;
                        font-size: 14px;
                    }
                }
            }

            .text-content {
                font-size: 16px;
                line-height: 1.6;
                color: #333;
                margin: 12px 0;

                &.loading {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    height: 24px;

                    .dot {
                        width: 8px;
                        height: 8px;
                        margin: 0 4px;
                        background-color: #666;
                        border-radius: 50%;
                        display: inline-block;
                        animation: dot-flashing 1s infinite linear alternate;

                        &:nth-child(2) {
                            animation-delay: 0.2s;
                        }

                        &:nth-child(3) {
                            animation-delay: 0.4s;
                        }
                    }
                }
            }
        }

        .message-actions {
            display: flex;
            justify-content: flex-end;
            margin-top: 16px;

            .action-buttons {
                display: flex;
                gap: 16px;

                .action-icon {
                    font-size: 18px;
                    color: #666;
                    cursor: pointer;
                    padding: 4px;
                    border-radius: 4px;
                    transition: all 0.3s ease;

                    &:hover {
                        color: #409EFF;
                        background-color: rgba(64, 158, 255, 0.1);
                    }
                }
            }
        }

        .related-questions {
            margin-top: 16px;
            display: flex;
            flex-direction: column;
            gap: 8px;

            .related-question {
                background-color: #fff;
                padding: 12px 16px;
                border-radius: 8px;
                cursor: pointer;
                transition: all 0.3s ease;
                color: #666;

                &:hover {
                    background-color: #f0f0f0;
                    color: #409EFF;
                }
            }
        }
    }
}

.chat-input-section {
    padding: 20px;
    background-color: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    .input-wrapper {
        max-width: 800px;
        margin: 0 auto;

        .input-container {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .input-field {
            flex: 1;

            .main-input {
                :deep(.el-input__inner) {
                    height: 44px;
                    padding: 0 15px;
                    font-size: 16px;
                    border-radius: 22px;
                    background-color: #f5f7fa;
                    border: 1px solid #dcdfe6;

                    &:focus {
                        background-color: #fff;
                        border-color: #409EFF;
                    }
                }

                :deep(.el-input__prefix),
                :deep(.el-input__suffix) {
                    display: flex;
                    align-items: center;
                    color: #909399;
                }
            }
        }

        .send-button {
            width: 44px;
            height: 44px;
            border-radius: 22px;
            background-color: #409EFF;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
            flex-shrink: 0;

            &.disabled {
                background-color: #a0cfff;
                cursor: not-allowed;
            }

            i {
                color: white;
                font-size: 20px;
            }

            &:hover:not(.disabled) {
                background-color: #66b1ff;
                transform: scale(1.05);
            }
        }
    }
}

@keyframes dot-flashing {
    0% {
        opacity: 0.2;
        transform: scale(0.8);
    }
    100% {
        opacity: 1;
        transform: scale(1);
    }
}
</style>